<?php
require_once( '../system/smarty.inc' );
require_once( '../system/mdao/Class_D_DNP_AREA.php' );
require_once( '../system/mdao/Class_M_PATTERN.php' );

require_once( '../system/mdao/Class_D_DNP_AREA_SHOP.php');
require_once( '../system/mdao/Class_M_OTHER.php' );
require_once( '../system/Class_ERROR.php' );
require_once( '../system/Class_PWD.php' );
require_once( '../system/login.inc.php' );

Class_PWD::valid_auth(AOKI_AUTH_DNP_AREA, $login['staff_auth']);

$editflg = 1; //1 編集可能　2 部数だけ編集可能
$is_shop = 2; //1 店舗可能　2　店舗不可 
$isG5 = FALSE ;
if   ($login['staff_auth'] == 'G-5') {
	/*
	if( isset($_GET['isshop']) && $_GET['isshop'] != '' ){
		echo "アクセス不可";
		exit;
	}
	*/
	$isG5 = TRUE ;
	$editflg = 2;
}

$dao  = new Class_D_DNP_AREA ;
if( $_SERVER['REQUEST_METHOD'] == 'GET' ){
	$phase = 'input';
	if( isset($_GET['id']) && $_GET['id'] != '' ){
		$forms  =  $dao->get( $_GET['id'] );
		$dists  =  Class_M_OTHER::get_dist_array( );
		$hands  =  Class_M_OTHER::get_hand_array( );
		//print_r($hands);
		$forms["dist_name"] = $dists[$forms["dist_id"]];
		$forms["hand_name"] = $hands[ $forms["hand_cd"] ];
		
		$daoadshop = new Class_D_DNP_AREA_SHOP($dao->get_db());
		//$disp_ng = $forms["disp_ng"]?$forms["disp_ng"]:0;
		
		$dbarray = $dao->getShops($_GET['id'] );
		//データ整形
		foreach ($dbarray as $k=>$v) {
			$forms["mutirow"] []=array("shop_cd"=> $v["shop_cd"], "shop_name" => $v["shop_name"], "year_sale" => $v["year_sale"], "shop_per" => $v["shop_per"], "shop_nums" => $v["shop_nums"]);
		}
		
		$formsc_shop_per  =  0;
		$formsc_shop_nums =  0;
		if ( $forms["center_flg"] == "1" ) {
			foreach ($dbarray as $k=>$v) {
				$formsc_shop_per = $formsc_shop_per   + $v["shop_per"];
				$formsc_shop_nums = $formsc_shop_nums + $v["shop_nums"];
			}
		}
	}
	
	$pdao = new Class_M_PATTERN ;  
	if ( isset($_GET['p']) && $_GET['p'] != '' ){
		if ( $patterns  = $pdao->get( $_GET['p'] ) ) {
			$forms["pattern_cd"]   =  $patterns["pattern_cd"];
			$forms["pattern_name"] =  $patterns["pattern_name"];
		}
	}else {
		echo "パターンエラー";
		exit;
	}
	
	if( isset( $forms['center_flg'] ) && ($forms['center_flg'] == '1') ){
		 $forms['hcenter_flg'] = 1;
	}else {
		 $forms['hcenter_flg'] = 0;
	}
	//都心計算
	$centernums =  $dao->getcentercount( $forms["pattern_cd"] );

	$centernums["c_area_nums"] = empty($centernums["c_area_nums"]) ? 0 : $centernums["c_area_nums"] ;
	$centernums["c_shop_per"]  = empty($centernums["c_shop_per"] ) ? 0 : $centernums["c_shop_per"] ;
	$centernums["c_shop_nums"] = empty($centernums["c_shop_nums"]) ? 0 : $centernums["c_shop_nums"] ;
	if( isset($_GET['id']) && $_GET['id'] != '' ){
		if ( $forms["center_flg"] == "1" ) {
			$forms["c_area_nums"] = $centernums["c_area_nums"] -  $forms["area_nums"] ;
			$forms["c_shop_per"]  = $centernums["c_shop_per"]  -  $formsc_shop_per ;
			$forms["c_shop_nums"] = $centernums["c_shop_nums"] -  $formsc_shop_nums ;
		}else {
			$forms["c_area_nums"] = $centernums["c_area_nums"]  ;
			$forms["c_shop_per"]  = $centernums["c_shop_per"]   ;
			$forms["c_shop_nums"] = $centernums["c_shop_nums"] ;
		}
	}
}else{
	$forms   =   $_POST;
	
	if( $forms['mode'] == 'delete' ){
	
		if ($dao->delAll( $forms['id'] )){
			$smarty->assign('message', '削除が成功しました。');
		}else {
			$smarty->assign('message', '削除が失敗しました。');
		} 
		
			$smarty->assign('phase', "delete" );
			$smarty->assign('menu', $smarty->fetch('menu.html') );
			$smarty->assign('logout', $smarty->fetch('logout.html') );
			$smarty->assign('footer', $smarty->fetch('footer.html') );
			
			$smarty->display('ddnparea_form.html');
	
		exit;
	}
	
	//echo "**".$is_shop."**";
	if (isset($forms["shop_cd"])) {
		foreach ($forms["shop_cd"] as $k=>$v) {
			$forms["mutirow"] []=array("shop_cd"=> $v, "shop_name" => $forms["shop_name"][$k], "year_sale" => $v["year_sale"], "shop_per" => $forms["shop_per"][$k], "shop_nums" => $forms["shop_nums"][$k]);
		}
	} 
	if( $forms['mode'] == 'input' ){
		$err     = new Class_ERROR;
		$chk     = $dao->get_checks();
		
		foreach ($chk as $kcol => $chkval) {
			$err_mes[$kcol]  = $err->check( $forms[$kcol], $chkval );
		}
		$index = 0;
		$daoadshop =new Class_D_DNP_AREA_SHOP($dao->get_db());
		$chkadshop     = $daoadshop->get_checks();
		foreach($forms["mutirow"] as $k=>$v) {
			$err_mes["shop_per"][$index]   = $err->check( $v["shop_per"],  $chkadshop["shop_per"] );
			$err_mes["shop_nums"][$index]  = $err->check( $v["shop_nums"], $chkadshop["shop_nums"] );
			$index = $index + 1;
		}
		$forms["dist_id"]           =  Class_M_OTHER::get_dist_id($forms["dist_name"]);
		if( $forms['id'] != '' ){
			$err_mes["mutirow"] = $err->check( $forms["mutirow"],array( "EXIST" ));
			$where = sprintf(" pattern_cd = '%s' and dist_id  = '%s'  and id <> '%s'", $forms['pattern_cd'], $forms["dist_id"], $forms['id'] );
			if ( $dao->exits($where) ) {
					$err->clear = false;
					$err_mes['dist_id'] = '<p class="error">このパターンエリアは重複しています</p>';
				}
		}else {
			
			if( $err_mes['dist_id'] == '' ){
				$where = sprintf(" pattern_cd = '%s' AND dist_id ='%s' ", $forms['pattern_cd'], $forms["dist_id"] );
				if ( $dao->exits($where) ) {
					$err->clear = false;
					$err_mes['dist_id'] = '<p class="error">このパターンエリアは重複しています</p>';
				}
			}
		}
		if( $err->clear ){
			if( $forms['id'] == '' ){
				try {
					$dao->begin_trans();
					$executeflg = TRUE;
					$values = array();
					$values["pattern_cd"]        =  $forms["pattern_cd"];
					if (!$forms["dist_id"]){
						$values["dist_id"]         =  Class_M_OTHER::do_dist($forms["dist_name"]);
					}else{
						$values["dist_id"]         =  $forms["dist_id"];
					}
					//
					//class_M_OTHER::do_area($values["area_name"]);
					$values["hand_cd"]           =   Class_M_OTHER::do_hand($forms["hand_name"]);
					$values["area_nums"]         =  $forms["area_nums"];
					$values["center_flg"]        =  $forms["center_flg"]=='1' ? 1 :  0;
					print_r($values);
					if ($dnpid = $dao->add($values)) {
						foreach($forms["mutirow"] as $kk=>$vv) {
							$shopval["dnpid"]         = $dnpid ;
							$shopval["shop_cd"]       = $vv["shop_cd"] ;
							$shopval["shop_name"]     = $vv["shop_name"] ;
							$shopval["shop_per"]      = $vv["shop_per"] ;
							$shopval["shop_nums"]     = $vv["shop_nums"] ;
							if ($daoadshop->add0($shopval)) {
							} else {
								$executeflg = FALSE;
								break;
							}
						}
					} else {
						$executeflg = FALSE;
					}
					if  ($executeflg) {
						if ( $forms["center_flg"] == "1" || $forms["hcenter_flg"] == "1"  ) {
							$centerSum =  $forms["c_area_nums"]  ;
							if ( $forms["center_flg"] == "1" ){
								$centerSum =  $centerSum + $forms["area_nums"];
							}
							if  (!($dao->updateCenterShops($forms["pattern_cd"], $centerSum))){
								$executeflg = FALSE;
							}
						}
					}
					if ($executeflg) {
						$dao->commit_trans();
						$smarty->assign('message', '登録が完了しました。');
					} else {
						$dao->rollback_trans();
						$smarty->assign('message', '登録が失敗しました。');
					}
				} catch (Exception $e) {
						$dao->rollback_trans();
						$smarty->assign('message', 'ＤＢエラーで失敗しました。');
				}
			}else{
				/*更新か削除かチェック整形*/
				$dataadd  = array();
				$datadel  = array();
				$dataedit = array();
				try {
					$executeflg = TRUE;
					$dao->begin_trans();
					$values = array();
					$values["pattern_cd"]        =  $forms["pattern_cd"];
					if (!$forms["dist_id"]){
						$values["dist_id"]         =  Class_M_OTHER::do_dist($forms["dist_name"]);
					}else{
						$values["dist_id"]         =  $forms["dist_id"];
					}
					//
					$values["hand_cd"]           =  Class_M_OTHER::do_hand($forms["hand_name"]);
					$values["area_nums"]         =  $forms["area_nums"];
					$values["center_flg"]        =  $forms["center_flg"]=='1' ? 1 :  0;
					
					if ($dao->edit( $forms['id'], $values )) {
						/*
						if ($dao->updateShopNums( $forms['id'], $values["area_nums"])) {
							$executeflg = TRUE;
						}else {
							$executeflg = FALSE;
						}
						*/
						if ( $forms["center_flg"] == "1" || $forms["hcenter_flg"] == "1"  ) {
							$centerSum =  $forms["c_area_nums"]  ;
							
							if ( $forms["center_flg"] == "1" ){
								$centerSum =  $centerSum + $forms["area_nums"];
							}
							if  (!($dao->updateCenterShops($forms["pattern_cd"], $centerSum))){
								$executeflg = FALSE;
							}
						}
					} else {
						$executeflg = FALSE;
					}
					//店舗DBの更新
					if ($executeflg){
						//$disp_ng = $forms["disp_ng"]?$forms["disp_ng"]:0;
						$wherearr[] = sprintf(" dnpid =  '%s' ", $forms['id'] );
						$dbarray = $daoadshop->search($wherearr );
						//削除.更新のデータ作成
						foreach($dbarray as $k=>$v) {
							$delflg = TRUE;
							$val_shop_nums = "0";
							$val_shop_per  = "0";
							foreach($forms["mutirow"] as $kk=>$vv) {
								if ($v["shop_cd"] == $vv["shop_cd"] ) {
									$delflg = FALSE;
									$val_shop_nums = $vv["shop_nums"];
									$val_shop_per  = $vv["shop_per"];
									break;
								}
							}
							if ($delflg){
								if ($daoadshop->remove($v["id"])) {
								} else {
									$executeflg = FALSE;
								}
							} else {
								$values = array();
								$values["shop_nums"] = $val_shop_nums;
								$values["shop_per"]  = $val_shop_per;
								if ($daoadshop->edit( $v["id"] ,$values)) {
								} else {
									$executeflg = FALSE;
								}
							}
						}
						//追加のデータ作成
						foreach($forms["mutirow"] as $k=>$v) {
							$taddflg = TRUE;
							foreach($dbarray as $kk=>$vv) {
								if ($v["shop_cd"] == $vv["shop_cd"] ) {
									$taddflg = FALSE;
									break;
								}
							}
							if ($taddflg){
								$values = array();
								$values["dnpid"]           = $forms['id'];
								$values["shop_cd"]         = $v["shop_cd"] ;
								$values["shop_name"]       = $v["shop_name"] ;
								$values["shop_per"]        = $v["shop_per"] ;
								$values["shop_nums"]       = $v["shop_nums"] ;
								if ($daoadshop->add0($values)) {
								} else {
									$executeflg = FALSE;
								}
							}
						}
					}
					if  ($executeflg) {
						$dao->commit_trans();
						$smarty->assign('message', '更新が完了しました。');
					} else {
						$dao->rollback_trans();
						$smarty->assign('message', '更新が失敗しました。');
					}
				} catch (Exception $e) {
					$dao->rollback_trans();
					$executeflg = FALSE;
					$smarty->assign('message', 'ＤＢエラーで失敗しました。');
				}
			}
			$phase = 'complete';
		}else{
			$phase = 'input';
		}
	}
}
	if(isset($forms['id']) && $forms['id'] == '' ) {
		$editflg  = 1;
	}
	$smarty->assign('isG5', $isG5 );
	$smarty->assign('editflg', $editflg);
	$smarty->assign('isshop', $is_shop);
	
	//print_r( $err_mes );
	if( isset( $forms ) ) $smarty->assign('forms', $forms);
	if( isset( $err_mes ) ) $smarty->assign('err', $err_mes);
	
	$smarty->assign('phase', $phase );
	$smarty->assign('menu', $smarty->fetch('menu.html') );
	$smarty->assign('logout', $smarty->fetch('logout.html') );
	$smarty->assign('footer', $smarty->fetch('footer.html') );
	
	$smarty->display('ddnparea_form.html');
	
	function updateCenter($dao, $inCenterFlg,  $inc_area_nums, $inarea_nums) {
		

	}
	
	
?>